var keyCode = Public.keyCode, ENTER = keyCode.ENTER, TAB = keyCode.TAB, F7 = keyCode.F7, SPACE = keyCode.SPACE, F12 = keyCode.F12, KEY_S = keyCode.S, ESC = keyCode.ESCAPE;
var Voucher = Voucher || {}; 
Voucher.items = {}, Voucher.voucherWrap = $('.voucherWrap');
Voucher.colTotal = $('.col_total');
Voucher.SubjectsData=[]
/**
 *初始化事件
 */
Voucher.initEvent = function() {
    Voucher.activateEdit();
    var SubjectTree;
    //删除分录
    $('#voucherTable').on('click', '.del', function(e) {
        e.preventDefault();
        Voucher.delEntry($(this).parents('.entry_item'));
    });

    //增加分录
    $('#voucherTable').on('click', '.add', function(e) {
        e.preventDefault();
        Voucher.addEntry($(this).parents('.entry_item'));
    });

    //科目弹窗
    $('#voucherTable').on('click', '.selSub', function(e) {
        if (!SubjectTree) {

        }
        Business.subjectTreePop($(this), function(data, target) {
            target = target.parents("tr");
            target.find('.col_subject').trigger('click');
            Voucher.subjectFeild.getCombo().selectByValue(data.id);
            Voucher._focusJump(target, data, false);
        }, true);
    });


    //查询余额
    $('.balance').live('click', function(e) {
        e.stopPropagation();
        Voucher.showCheckBalance($(this));
    });

    //点击页面其他地方关闭编辑
    $(document).on('click', function(e) {
        var target = e.target;
        //点击非录入区域时，关闭编辑状态
        if (Voucher.balancePop && Voucher.balancePop.is(':visible')) {
            Voucher.balancePop.hide().find('.check-balance').html('查询中...');
        }
        if ($(target).closest('#voucherTable td[data-edit]').length == 0) {
            if ($(target).closest('#isItem').length == 0) {
                Voucher.cancelEdit();
            }
        }
    });
    if(Voucher.SubjectsData.length < 1) {
        $.ajax({
            type: "get",
            url: _APP_ + '/Accounting/AccountingSubject/ajax_getSubject',
            async: false,
            success: function(data) {
                if (data.error) {
                    alert(error);
                } else {
                    Voucher.SubjectsData = data.items;
                }
            }
        });
    }

}

/**
 *激活编辑事件
 */
Voucher.activateEdit = function() {
    //点击编辑
    $('#voucherTable').on('click', 'td[data-edit]', function(e) {
        Voucher.editCell($(this));
    });

    //显示划过状态
    $('#voucherTable').on('mouseover', 'tbody .entry_item', function(e) {
        $(this).addClass("current").siblings().removeClass("current");
    });
    $('#voucherTable').on('mouseleave', 'tbody .entry_item', function(e) {
        $(this).removeClass("current");
    });
}


/**
 *取消编辑事件
 */
Voucher.deactivateEdit = function() {
    $('#voucherTable').off('click', 'td[data-edit]');
    $('#voucherTable').off('mouseover', 'tbody .entry_item');
    $('#voucherTable').off('mouseleave', 'tbody .entry_item');

    Voucher.cancelEdit();
}


/**
 *编辑单元格
 */
Voucher.editCell = function(cell) {
    if (cell.data('onEdit')) {
        return;
    }
    if (Voucher.curEditCell) {
        if (!Voucher.cancelEdit()) {
            return false;
        }
    }
    Voucher.curEditCell = cell.data('onEdit', true);
    var editType = cell.attr('data-edit');
    var valObj = cell.find('.cell_val').hide();
    var curVal, subjectInfo;
    if (!editType) {
        return;
    }
    switch (editType) {
        case 'summary':
            Voucher.curEditField = $('#voucherTable .edit_summary');
            if (Voucher.curEditField.length == 0) {
                Voucher.createSummaryFeild();
                Voucher.curEditField = Voucher.summaryFeild;
            }
            curVal = valObj.text();
            break;
        case 'subject':
            Voucher.curEditField = $('#voucherTable .edit_subject');
            if (Voucher.curEditField.length == 0) {
                Voucher.createSubjectFeild();
                Voucher.curEditField = Voucher.subjectFeild;
            }
            subjectInfo = valObj.data('subjectInfo');
//            console.debug(subjectInfo);
            if (subjectInfo) {
                curVal = subjectInfo.number + ' ' + subjectInfo.fullName;
            } else {
                curVal = '';
            }
            break;
        case 'money':
            Voucher.curEditField = $('#voucherTable .edit_money');
            if (Voucher.curEditField.length == 0) {
                Voucher.createMoneyFeild();
                Voucher.curEditField = Voucher.moneyFeild;
            }
            curVal = valObj.data('realValue');
            if (curVal == 0) {
                curVal = '';
            }
            break;
    }
    Voucher.curEditField.insertAfter(valObj).show();//.select().focus();

    if (editType == 'subject') {
        Voucher.curEditField.getCombo().selectByText(curVal, false);
    } else {
        Voucher.curEditField.val(curVal);
    }

    window.setTimeout(function() {
        if (Voucher.curEditField.val()) {
            Voucher.curEditField.select();
        } else {
            Voucher.curEditField.select().focus();
        }
    }, 0);
}


/**
 *取消编辑
 */
Voucher.cancelEdit = function() {
    if (!Voucher.curEditCell) {
        return;
    }
    var cell = Voucher.curEditCell, val = realValue = Voucher.curEditField.val(), valObj = cell.find('.cell_val'),
            itemsData = valObj.data('itemsData'), subjectInfo = valObj.data('subjectInfo');
    if (cell.data('edit') == 'money') {
        val = parseFloat(val);
        if (isNaN(val)) {
            val = 0;
        } else if (Math.abs(val) >= 1000000000) {
            val = 0;
            Public.tips({type: 2, content: '只能输入10亿以下的金额！'});
        }
        Voucher.showAmout(valObj, val);
        Voucher.calTotalAmount();
    } else if (cell.data('edit') == 'subject') {
        if (!Voucher._checkItems()) {
            return false;
        } else {
            $('#isItem').hide();
        }
        if ($('#voucherTable .edit_subject').length > 0) {
            val = $('#voucherTable .edit_subject').getCombo().getText();
            if (subjectInfo && subjectInfo.isItem) {
                val += '<span>_';
                var itemArr = ["itemKH", "itemGYS", "itemZY", "itemXM", "itemBM", "itemCH", "itemZDY", "itemSFXD"];
                for (var i = 0, len = itemArr.length; i < len; i++) {
                    var itemData = itemsData[itemArr[i]];
                    if (itemData) {
                        var number = itemData.number || '';
                        val += number + '' + itemData.name + '_';
                    }
                }
                val = val.slice(0, val.length - 1);
                val += '</span>'
            }
        } else {
            val = '';
        }
        ;
        valObj.html(val);
    } else {
        valObj.text(val);
    }
    valObj.show();
    Voucher.curEditField.hide();
    cell.data('onEdit', false);
    Voucher.curEditCell = null;
    return true;
}



/**
 *生成摘要文本域
 */
Voucher.createSummaryFeild = function() {
    var tr = $("#voucherTable tbody tr.entry_item");
    var firstTr = $("#voucherTable tbody tr:first-child");
    Voucher.summaryFeild = $('<textarea class="edit_summary" />').on('keydown', function(e) {
        var keyValue = e.which, parentTr = $(this).parents('tr.entry_item'), lastTr = parentTr.prev();
        if (e.shiftKey && (keyValue == ENTER || keyValue == TAB)) {
            if (lastTr.length === 0) {
                $('#vch_date').focus();
            } else {
                Voucher.setAmountFocus(lastTr);
            }
            return false;
        }

        switch (keyValue) {
            case ENTER:
            case TAB:
                e.preventDefault();
                parentTr.find('.col_subject').trigger('click');
                break;
        }
        ;
        //TODO .. //快捷键
    }).on('focus', function(e) {
        //如果无值，则取上一条有值的摘要内容
        if ($(this).val())
            return;
        var summaryObjs = $('#voucherTable .summary_val');
        var index = $(this).prev('.summary_val').index('#voucherTable .summary_val');
        var val;
        for (var i = index - 1; i >= 0; i--) {
            val = $.trim(summaryObjs.eq(i).text());
            if (val) {
                $(this).val(val);
                return;
            }
        }
        ;
    }).on('keyup', function() {
        var parentTr = $(this).parents('tr.entry_item'), lastTr = parentTr.prev();
        var curValue = $(this).val(), curIndex = tr.index(parentTr);
        if (lastTr.length === 0)
            return;
        if (curValue === "//") {// 快捷键“//”复制第一条分录摘要
            $(this).val(firstTr.find(".summary_val").html());
        } else if (curValue === "..") {// 快捷键“..”复制上一条分录摘要                    
            var prevSummary = lastTr.find(".summary_val").html();
            $(this).val(prevSummary);
        }
    })
}

/**
 *生成科目编辑域
 */
Voucher.createSubjectFeild = function() {
    Voucher.subjectFeild = $('<input type="text" class="edit_subject" autocomplete="off" />').combo({
        data: function() {
            return Voucher.SubjectsData;
        },
        formatText: function(data) {
            return data.number + ' ' + data.fullName;
        },
        value: 'id',
        defaultSelected: -1,
        editable: true,
        customMatch: function(text, query) {
            query = query.toLowerCase().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
            var idx = text.toLowerCase().search(query);
            if (/^\d+$/.test(query)) {
                if (idx == 0) {
                    return true;
                }
            } else {
                if (idx != -1) {
                    return true;
                }
            }
            return false;
        },
//			extraListHtml: '<a href="javascript:void(0);" id="quickAddSubject" class="quick-add-link"><i class="ui-icon-add"></i>新增科目</a>',
        maxListWidth: 500,
        cache: false,
        forceSelection: true,
        maxFilter: 10,
        trigger: false,
        listHeight: 182,
        listWrapCls: 'ui-droplist-wrap ui-subjectList-wrap',
        callback: {
            onChange: function(data) {
                var parentTr = this.input.parents('tr.entry_item'), balance = parentTr.find(".balance");

                /*					if((Voucher.tempSubject == $('tr.entry_item').index(parentTr) && this.getSelectedIndex() !== -1) || this.getSelectedIndex() !== -1) {
                 Voucher.setAmountFocus(parentTr, data);
                 //Voucher._focusJump(this.input, data);
                 }*/
                //if(this.getSelectedIndex() === -1){
                this.input.prev('.cell_val').removeData('itemsData');
                $('#isItem').hide();
                parentTr.find('.quantity_val').html('');
                parentTr.find('.curr_val').html('');
                //}
                parentTr.find('.balance-pop').remove();
                parentTr.find('.option').removeClass('show');
                if (data) {
                    if (balance.length > 0) {
                        balance.attr("data-number", data.number);
                    } else {
                        parentTr.find(".option").append('<a class="balance" data-id =' + data.id + ' data-number =' + data.number + ' data-cur =' + data.cur + ' >余额</a>');
                    }
                } else {
                    balance.remove();
                }
                ;
                this.input.prev('.cell_val').data('subjectInfo', data);
            },
            onListClick: function() {
                var parentTr = this.input.parents('tr.entry_item');
                var subjectInfo = this.input.prev().data("subjectInfo");
                Voucher._focusJump(parentTr, subjectInfo);
                //Voucher.cancelEdit();
            }
        },
        queryDelay: 0,
        inputCls: 'edit_subject',
        wrapCls: 'edit_subject_wrap',
        focusCls: '',
        disabledCls: '',
        activeCls: ''
    }).bind('keydown', function(e) {
        var keyValue = e.which, parentTr = $(this).parents('tr.entry_item');
        if (e.shiftKey && (keyValue === ENTER || keyValue === TAB)) {
            parentTr.find('.col_summary').trigger('click');
            return false;
        }

        switch (keyValue) {
            case ENTER:
            case TAB:
                e.preventDefault();
                var subjectInfo = $(this).prev().data("subjectInfo");
                Voucher._focusJump(parentTr, subjectInfo);
                break;
            case F7:
                e.preventDefault();
                Business.subjectTreePop($(this), function(data, target) {
                    target.getCombo().selectByValue(data.id);
                }, true);
                break;
            case SPACE:
                return false;
            default:
                break;
        }

    }).bind('focus', function(e) {
        var $this = $(this);
        var subjectInfo = $this.prev().data("subjectInfo");
        window.setTimeout(function() {
            if (!subjectInfo && !$this.getCombo().isExpanded) {
                $this.getCombo().doQuery('');
            } else if (subjectInfo) {
                Voucher.originalSubject = subjectInfo.number;
                if (subjectInfo.isItem && !$('#isItem').is(':visible')) {
                    Voucher.createSubjectItem($this, subjectInfo);
                }
            } else {
                Voucher.originalSubject = '';
            }
            ;
        }, 0);
    });

    //快速新增
    var operateCallback = function(oper, data) {
        if (parent.parent['setting-subjectList']) {
            parent.parent['setting-subjectList'].SUBJECT_CHANGED_FLAG = true;
        }
        parent.SUB_SUBJECT_DATA = [];
        $.each(parent.SUBJECT_DATA, function(i, n) {
            if (n.detail) {
                parent.SUB_SUBJECT_DATA.push(n);
            }
        });
        var combo = Voucher.subjectFeild.getCombo();
        combo.loadData(parent.SUB_SUBJECT_DATA, ['id', data.id], true);
        var parentTr = Voucher.subjectFeild.parents('tr.entry_item');
        Voucher._focusJump(parentTr, data);
        combo.collapse();
        //Voucher.subjectFeild.focus();
    };
    $('#quickAddSubject').on('click', function(e) {
        e.preventDefault();
        $.dialog({
            title: '新增科目',
            content: 'url:../settings/subject-manage.html',
            data: {oper: 'add', rule: SYSTEM.RULE, classId: -1, subjectData: parent.SUBJECT_DATA, callback: operateCallback, isContinued: false},
            width: 450,
            height: 450,
            max: false,
            min: false,
            cache: false,
            lock: true
        });
    });
};


Voucher._focusJump = function(parentTr, data, edit) {
    if (!data) {
        parentTr.find(".col_debite").trigger("click");
        return;
    }
    ;
    var $_obj = parentTr.find('.edit_subject');
    var hasItem = data.isItem;
    var hasQtyaux = data.isQtyaux;
    var hasCurr = data.isCur;
    //无辅助核算、数量、外币直接跳转
    if (!hasItem && !hasQtyaux && !hasCurr) {
        if (edit) {	//生成编辑
            return;
        }
        Voucher.setAmountFocus(parentTr, data);
        return;
    }
    ;
    var trSiblings = parentTr.siblings();
    var cellVal = $_obj.prev('.cell_val');
    var currHtml = parentTr.find('.curr_val');
    var quantityHtml = parentTr.find('.quantity_val');

    var hasWhole = Voucher.voucherWrap.hasClass('has-whole');
    var hasCurrency = Voucher.voucherWrap.hasClass('has-currency');
    var hasAmount = Voucher.voucherWrap.hasClass('has-amount');

    var hasChange = Voucher.originalSubject === data.number ? false : true;

    //控制数量金额页面显示
    if (hasQtyaux) {
        if (hasChange || quantityHtml.html() === '') {
            var unitStr = '', acctUnit = '';
            if ($.trim(data.unit)) {
                unitStr = data.unit;
            }
            ;

            acctUnit = data.acctUnit || data.unit;

            var quantity = '<p class="mb8">数量:<input type="text" class="quantity numerical" /><span class="unit" data-unit="' + acctUnit + '">' + unitStr + '</span></p><p>单价:<input type="text" class="unit-price numerical" /></p>';
            quantityHtml.html(quantity);
            if (edit) {
                quantityHtml.find('.quantity').val(data.qty);
                quantityHtml.find('.unit-price').val(data.price);
            }
        }
    } else {
        quantityHtml.html('');
    }

    //控制多币别页面显示
    if (hasCurr) {
        if (hasChange || currHtml.html() === '') {
            var optionHtml = '', thisCur = edit ? eval(data.acctCur) : eval(data.cur);
            for (var i = 0, len = thisCur.length; i < len; i++) {
                optionHtml += '<option value="' + thisCur[i] + '">' + thisCur[i] + '</option>'
            }
            currHtml.html('<p class="mb8"><select class="curr-code">' + optionHtml + '</select><input type="text" class="rate numerical" /></p><p>原币:<input type="text" class="original numerical" /></p>');
            var $_currCode = currHtml.find('.curr-code');
            var $_rate = currHtml.find('.rate');
            var $_original = currHtml.find('.original');
            if (edit) {
                $_currCode.val(data.cur);
                currHtml.find('.rate').val(data.rate);
                currHtml.find('.original').val(data.amountFor);
            } else {
                currHtml.find('.rate').val(Number(SYSTEM.CurRate[thisCur[0]]));
            }
            if ($_currCode.val() === SYSTEM.CURRENCY) {
                $_rate.attr('disabled', 'disabled');
                $_original.attr('disabled', 'disabled');
            }
        }
    } else {
        currHtml.html('');
    }

    $('.numerical').numberField({decimal: true, precision: 6});

    if (!hasWhole) {
        if (hasQtyaux && hasCurr) {
            Voucher.voucherWrap.addClass('has-whole');
            Voucher.colTotal.attr('colspan', '5');
        } else if (hasQtyaux) {
            if (!hasAmount) {
                if (hasCurrency) {
                    Voucher.voucherWrap.removeClass('has-currency').addClass('has-whole');
                    Voucher.colTotal.attr('colspan', '5');
                } else {
                    Voucher.voucherWrap.addClass('has-amount');
                    Voucher.colTotal.attr('colspan', '4');
                }
            }
        } else if (hasCurr) {
            if (!hasCurrency) {
                if (hasAmount) {
                    Voucher.voucherWrap.removeClass('has-amount').addClass('has-whole');
                    Voucher.colTotal.attr('colspan', '5');
                } else {
                    Voucher.voucherWrap.addClass('has-currency');
                    Voucher.colTotal.attr('colspan', '4');
                }
            }
        }
    }

    //防止结构变化引起辅助核算移位
    if (hasItem) {
        if ($('#isItem').is(':visible')) {
            $('#isItem').find('input:visible').eq(0).focus();
        } else {
            if (!edit) {	//非编辑操作
                var inputList = Voucher.createSubjectItem($_obj, data);
                inputList.eq(0).focus();
            }
        }
    } else {
        cellVal.removeData('itemsData');
        $('#isItem').hide();
        if (!hasQtyaux && !hasCurr) {
            Voucher.setAmountFocus(parentTr, data);
            return;
        } else if (hasQtyaux) {
            Voucher.cancelEdit();
            parentTr.find('.quantity').focus();
        } else if (hasCurr) {
            Voucher.cancelEdit();
            parentTr.find('.curr-code').focus().click();
        }
    }

    if (hasQtyaux || hasCurr) {
        Voucher._focusJumpNext(parentTr, data, hasQtyaux, hasCurr);
    }
};

Voucher._checkQtyaux = function($_obj) {
    var hasQtyaux = false;
    $_obj.each(function(index, element) {
        var data = $(this).data('subjectInfo');
        if (data && data.isQtyaux) {
            hasQtyaux = true;
            return false;
        }
    });
    return hasQtyaux;
};

Voucher._checkCurr = function($_obj) {
    var hasCurr = false;
    $_obj.each(function(index, element) {
        var data = $(this).data('subjectInfo');
        if (data && data.isCur) {
            hasCurr = true;
            return false;
        }
    });
    return hasCurr;
};

Voucher._focusJumpNext = function(parentTr, data, hasQtyaux, hasCurr) {
    var hasQtyaux = hasQtyaux === undefined ? data.isQtyaux : hasQtyaux;
    var hasCurr = hasCurr === undefined ? data.isCur : hasCurr;

    if (hasQtyaux) { //有数量金额
        var quantityInput = parentTr.find('.quantity');
        var unitPriceInput = parentTr.find('.unit-price');

        quantityInput.bind("keydown", function(e) {
            if (e.which === 13) {
                unitPriceInput.focus();
            }
        }).bind('focus', function() {
            $(this).data("original", $(this).val());
        }).bind('blur', function() {
            Voucher._calculateQuantity(data, parentTr, $(this), quantityInput, unitPriceInput, hasCurr);
        });

        unitPriceInput.bind("keydown", function(e) {
            if (e.which === 13) {
                if (hasCurr) {  //有外币
                    parentTr.find('.curr-code').focus().click();
                } else {
                    $(this).blur();
                    Voucher.setAmountFocus(parentTr, data);
                }
            }
        }).bind('focus', function() {
            $(this).data("original", $(this).val());
        }).bind('blur', function() {
            Voucher._calculateQuantity(data, parentTr, $(this), quantityInput, unitPriceInput, hasCurr);
        });
    }
    if (hasCurr) {  //有外币
        var currSelect = parentTr.find('.curr-code');
        var rateInput = parentTr.find('.rate');
        var originalInput = parentTr.find('.original');

        currSelect.bind("keydown", function(e) {
            if (e.which === 13) {
                if ($(this).val() === SYSTEM.CURRENCY) {
                    rateInput.getNumberField().disable();//getNumberField
                    originalInput.getNumberField().disable();
                    originalInput.val('');
                    Voucher.setAmountFocus(parentTr, data);
                } else {
                    rateInput.getNumberField().enable();//getNumberField
                    originalInput.getNumberField().enable();
                    rateInput.focus();
                }
            }
        }).bind("change", function(e) {
            rateInput.val(Number(SYSTEM.CurRate[$(this).val()]));
            if ($(this).val() === SYSTEM.CURRENCY) {
                rateInput.getNumberField().disable();//getNumberField
                originalInput.getNumberField().disable();
                originalInput.val('');
            } else {
                rateInput.getNumberField().enable();//getNumberField
                originalInput.getNumberField().enable();
                Voucher._calculateCurrency(data, parentTr, $(this), rateInput, originalInput, hasQtyaux);
            }
        });

        rateInput.bind("keydown", function(e) {
            if (e.which === 13) {
                originalInput.focus();
            }
        }).bind('focus', function() {
            $(this).data("original", $(this).val());
        }).bind('blur', function() {
            Voucher._calculateCurrency(data, parentTr, $(this), rateInput, originalInput, hasQtyaux)
        });

        originalInput.bind("keydown", function(e) {
            if (e.which === 13) {
                $(this).blur();
                Voucher.setAmountFocus(parentTr, data);
            }
        }).bind('focus', function() {
            $(this).data("original", $(this).val());
        }).bind('blur', function() {
            Voucher._calculateCurrency(data, parentTr, $(this), rateInput, originalInput, hasQtyaux, true)
        });
    }
};
//正向数量核算金额计算
Voucher._calculateQuantity = function(data, parentTr, $_this, quantityInput, unitPriceInput, hasCurr) {
    var quantityVal = Number(quantityInput.val());
    var unitPriceVal = Number(unitPriceInput.val());
    var AmountPosition, debiteAmount = parentTr.find(".debit_val").text(), creditAmount = parentTr.find(".credit_val").text();
    if ($(".entry_item").index(parentTr) === 0) {
        AmountPosition = parentTr.find(".debit_val");
    } else {
        if (debiteAmount !== "") {
            AmountPosition = parentTr.find(".debit_val");
        } else if (creditAmount !== "") {
            AmountPosition = parentTr.find(".credit_val");
        } else if (data.dc == 1) {
            AmountPosition = parentTr.find(".debit_val");
        } else {
            AmountPosition = parentTr.find(".credit_val");
        }
    }

    if (($_this.val() !== $_this.data('original')) && quantityVal && unitPriceVal) {
        var thisTotal = Number(quantityVal) * Number(unitPriceVal);

        if (hasCurr) {  //有外币
            parentTr.find('.original').val(Number(thisTotal.toFixed(3)));
            var rateVal = parentTr.find('.rate').val();
            if (rateVal) {
                thisTotal = thisTotal * rateVal;
            } else {
                return;
            }
        }
        Voucher.showAmout(AmountPosition, thisTotal);
        Voucher.calTotalAmount();
    }
    ;
};
//正向外币核算金额计算
Voucher._calculateCurrency = function(data, parentTr, $_this, rateInput, originalInput, hasQtyaux, flag) {
    var rateVal = Number(rateInput.val());
    var originalVal = Number(originalInput.val());

    var AmountPosition, debiteAmount = parentTr.find(".debit_val").text(), creditAmount = parentTr.find(".credit_val").text();
    if ($(".entry_item").index(parentTr) === 0) {
        AmountPosition = parentTr.find(".debit_val");
    } else {
        if (debiteAmount !== "") {
            AmountPosition = parentTr.find(".debit_val");
        } else if (creditAmount !== "") {
            AmountPosition = parentTr.find(".credit_val");
        } else if (data.dc == 1) {
            AmountPosition = parentTr.find(".debit_val");
        } else {
            AmountPosition = parentTr.find(".credit_val");
        }
    }

    if (($_this.val() !== $_this.data('original')) && rateVal && originalVal) {
        var thisTotal = Number(rateVal) * Number(originalVal);
        //原币反算单价
        if (flag) {
            if (hasQtyaux) {  //有外币
                var quantityVal = parentTr.find('.quantity').val();
                if (quantityVal) {
                    parentTr.find('.unit-price').val(Number((Number(originalVal) / Number(quantityVal)).toFixed(3)));
                }
            }
        }
        Voucher.showAmout(AmountPosition, thisTotal);
        Voucher.calTotalAmount();
    }
}

Voucher.createSubjectItem = function($_obj, data) {
    var offset = $_obj.offset();
    var parentTr = $_obj.parents('tr.entry_item');
    var itemsData = jQuery.extend(true, {}, $_obj.prev('.cell_val').data('itemsData'));
    if (!Voucher.isItem) {
        Voucher.isItem = $('<div id="isItem"></div>');
        var insertItems = '<ul>' +
                '<li><label>客户:</label><span class="ui-combo-wrap" id="itemKH"><input type="text" class="input-txt" autocomplete="off" /><i class="trigger icon icon-caret-down"></i> </span></li>' +
                '<li><label>供应商:</label><span class="ui-combo-wrap" id="itemGYS"><input type="text" class="input-txt" autocomplete="off" /><i class="trigger icon icon-caret-down"></i> </span></li>' +
                '<li><label>职员:</label><span class="ui-combo-wrap" id="itemZY"><input type="text" class="input-txt" autocomplete="off" /><i class="trigger icon icon-caret-down"></i> </span></li>' +
                '<li><label>项目:</label><span class="ui-combo-wrap" id="itemXM"><input type="text" class="input-txt" autocomplete="off" /><i class="trigger icon icon-caret-down"></i> </span></li>' +
                '<li><label>部门:</label><span class="ui-combo-wrap" id="itemBM"><input type="text" class="input-txt" autocomplete="off" /><i class="trigger icon icon-caret-down"></i> </span></li>' +
                '<li><label>存货:</label><span class="ui-combo-wrap" id="itemCH"><input type="text" class="input-txt" autocomplete="off" /><i class="trigger icon icon-caret-down"></i> </span></li>' +
                '<li><label>自定义:</label><span class="ui-combo-wrap" id="itemZDY"><input type="text" class="input-txt" autocomplete="off" /><i class="trigger icon icon-caret-down"></i> </span></li>' +
                '<li><label>是否限定:</label><span class="ui-combo-wrap" id="itemSFXD"><input type="text" class="input-txt" autocomplete="off" /><i class="trigger icon icon-caret-down"></i> </span></li>' +
                '</ul>';
        Voucher.isItem.html(insertItems);
        $(".voucherWrap").append(Voucher.isItem);
    }
    ;
    var itemLi = Voucher.isItem.find('li');
//    console.debug(data);
    if (data.custom) {	//客户
        itemLi.eq(0).show();
        if (!Voucher.items.KH) {
            if (itemsData && itemsData.itemKH) {
                Voucher.items.KH = Voucher._instantItem($("#itemKH"), _APP_+'/Accounting/AccountingAssistItem/ajax_getItem?type=custom', $_obj, itemsData.itemKH.id);
            } else {
                Voucher.items.KH = Voucher._instantItem($("#itemKH"), _APP_+'/Accounting/AccountingAssistItem/ajax_getItem?type=custom', $_obj);
            }
        } else {
            //Voucher.items.KH.loadData(SYSTEM.itemKH);
            if (itemsData && itemsData.itemKH) {
                Voucher.items.KH.loadData(_APP_+'/Accounting/AccountingAssistItem/ajax_getItem?type=custom', ['id', itemsData.itemKH.id], false);
                //Voucher.items.KH.selectByValue(itemsData.itemKH.id);
            } else {
                Voucher.items.KH.loadData(_APP_+'/Accounting/AccountingAssistItem/ajax_getItem?type=custom', -1, false);
                //Voucher.items.KH.removeSelected();
            }
        }
    } else {
        itemLi.eq(0).hide();
    }
    ;
    if (data.supplier) {	//供应商
        itemLi.eq(1).show();
        if (!Voucher.items.GYS) {
            if (itemsData && itemsData.itemGYS) {
                Voucher.items.GYS = Voucher._instantItem($("#itemGYS"), '/bs/item?m=findItem&itemClassId=5', $_obj, itemsData.itemGYS.id);
            } else {
                Voucher.items.GYS = Voucher._instantItem($("#itemGYS"), '/bs/item?m=findItem&itemClassId=5', $_obj);
            }
        } else if (itemsData && itemsData.itemGYS) {
            Voucher.items.GYS.loadData('/bs/item?m=findItem&itemClassId=5', ['id', itemsData.itemGYS.id], false);
            //Voucher.items.GYS.selectByValue(itemsData.itemGYS.id);
        } else {
            Voucher.items.GYS.loadData('/bs/item?m=findItem&itemClassId=5', -1, false);
            //Voucher.items.GYS.removeSelected();
        }
    } else {
        itemLi.eq(1).hide();
    }
    ;
    if (data.emp) {	//职员
        itemLi.eq(2).show();
        if (!Voucher.items.ZY) {
            if (itemsData && itemsData.itemZY) {
                Voucher.items.ZY = Voucher._instantItem($("#itemZY"), '/bs/item?m=findItem&itemClassId=2', $_obj, itemsData.itemZY.id);
            } else {
                Voucher.items.ZY = Voucher._instantItem($("#itemZY"), '/bs/item?m=findItem&itemClassId=2', $_obj);
            }
        } else if (itemsData && itemsData.itemZY) {
            Voucher.items.ZY.loadData('/bs/item?m=findItem&itemClassId=2', ['id', itemsData.itemZY.id], false);
            //Voucher.items.ZY.selectByValue(itemsData.itemZY.id);
        } else {
            Voucher.items.ZY.loadData('/bs/item?m=findItem&itemClassId=2', -1, false);
            //Voucher.items.ZY.removeSelected();
        }
    } else {
        itemLi.eq(2).hide();
    }
    ;
    if (data.project) {	//项目
        itemLi.eq(3).show();
        if (!Voucher.items.XM) {
            if (itemsData && itemsData.itemXM) {
                Voucher.items.XM = Voucher._instantItem($("#itemXM"), '/bs/item?m=findItem&itemClassId=3', $_obj, itemsData.itemXM.id);
            } else {
                Voucher.items.XM = Voucher._instantItem($("#itemXM"), '/bs/item?m=findItem&itemClassId=3', $_obj);
            }
        } else if (itemsData && itemsData.itemXM) {
            Voucher.items.XM.loadData('/bs/item?m=findItem&itemClassId=3', ['id', itemsData.itemXM.id], false);
            //Voucher.items.XM.selectByValue(itemsData.itemXM.id);
        } else {
            Voucher.items.XM.loadData('/bs/item?m=findItem&itemClassId=3', -1, false);
            //Voucher.items.XM.removeSelected();
        }
    } else {
        itemLi.eq(3).hide();
    }
    ;
    if (data.dept) {	//部门
        itemLi.eq(4).show();
        if (!Voucher.items.BM) {
            if (itemsData && itemsData.itemBM) {
                Voucher.items.BM = Voucher._instantItem($("#itemBM"), '/bs/item?m=findItem&itemClassId=6', $_obj, itemsData.itemBM.id);
            } else {
                Voucher.items.BM = Voucher._instantItem($("#itemBM"), '/bs/item?m=findItem&itemClassId=6', $_obj);
            }
        } else if (itemsData && itemsData.itemBM) {
            Voucher.items.BM.loadData('/bs/item?m=findItem&itemClassId=6', ['id', itemsData.itemBM.id], false);
            //Voucher.items.BM.selectByValue(itemsData.itemBM.id);
        } else {
            Voucher.items.BM.loadData('/bs/item?m=findItem&itemClassId=6', -1, false);
            //Voucher.items.BM.removeSelected();
        }
    } else {
        itemLi.eq(4).hide();
    }
    ;
    if (data.inventory) {	//存货
        itemLi.eq(5).show();
        if (!Voucher.items.CH) {
            if (itemsData && itemsData.itemCH) {
                Voucher.items.CH = Voucher._instantItem($("#itemCH"), '/bs/item?m=findItem&itemClassId=4', $_obj, itemsData.itemCH.id);
            } else {
                Voucher.items.CH = Voucher._instantItem($("#itemCH"), '/bs/item?m=findItem&itemClassId=4', $_obj);
            }
        } else if (itemsData && itemsData.itemCH) {
            Voucher.items.CH.loadData('/bs/item?m=findItem&itemClassId=4', ['id', itemsData.itemCH.id], false);
            //Voucher.items.CH.selectByValue(itemsData.itemCH.id);
        } else {
            Voucher.items.CH.loadData('/bs/item?m=findItem&itemClassId=4', -1, false);
            //Voucher.items.CH.removeSelected();
        }
    } else {
        itemLi.eq(5).hide();
    }
    ;

    if (data.itemClassId > 0) {	//自定义
        itemLi.eq(6).show().find('label').text(data.itemClassName + ':');
        if (!Voucher.items.ZDY) {
            if (itemsData && itemsData.itemZDY) {
                Voucher.items.ZDY = Voucher._instantItem($("#itemZDY"), '/bs/item?m=findItem&itemClassId=' + data.itemClassId, $_obj, itemsData.itemZDY.id);
            } else {
                Voucher.items.ZDY = Voucher._instantItem($("#itemZDY"), '/bs/item?m=findItem&itemClassId=' + data.itemClassId, $_obj);
            }
        } else {
            if (itemsData && itemsData.itemZDY) {
                Voucher.items.ZDY.loadData('/bs/item?m=findItem&itemClassId=' + data.itemClassId, ['id', itemsData.itemZDY.id], false);
                //Voucher.items.ZDY.selectByValue(itemsData.itemZDY.id);
            } else {
                Voucher.items.ZDY.loadData('/bs/item?m=findItem&itemClassId=' + data.itemClassId, -1, false);
            }
        }

    } else {
        itemLi.eq(6).hide();
    }
    ;

    if (data.limited === 3) {	//是否限定
        itemLi.eq(7).show();
        if (!Voucher.items.SFXD) {
            if (itemsData && itemsData.itemSFXD) {
                Voucher.items.SFXD = Voucher._instantXDItem($("#itemSFXD"), $_obj, String(itemsData.itemSFXD.id));
            } else {
                Voucher.items.SFXD = Voucher._instantXDItem($("#itemSFXD"), $_obj);
            }
        } else {
            if (itemsData && itemsData.itemSFXD) {
                Voucher.items.SFXD.selectByValue(String(itemsData.itemSFXD.id), true);
                //Voucher.items.ZDY.selectByValue(itemsData.itemZDY.id);
            } else {
                //Voucher.items.SFXD._selectedIndex = -1;
                Voucher.items.SFXD.selectByIndex(-1, true);
            }
        }

    } else {
        itemLi.eq(7).hide();
    }
    ;

    Voucher.isItem.css({
        "top": (offset.top + $_obj.height() -13) + "px",
        "left": (offset.left-39) + "px"
    }).show();

    var comboList = Voucher.isItem.find("li:visible");
    var inputList = comboList.find("input");

    var len = comboList.length;
    var hasQtyaux = data.isQtyaux;
    var hasCurr = data.isCur;
    inputList.unbind("keydown.fast").bind("keydown.fast", function(e) {
        if (e.which === 13) {
            var pos = parseInt(inputList.index(this));
            comboList.eq(pos).find('.ui-combo-wrap').getCombo().blur();
            if (pos < len - 1) {
                inputList.eq(pos + 1).focus();
            } else {
                if (Voucher._checkItems(comboList)) {
                    if (!hasQtyaux && !hasCurr) {
                        Voucher.setAmountFocus(parentTr, data);
                        return;
                    } else if (hasQtyaux) {
                        Voucher.cancelEdit();
                        parentTr.find('.quantity').focus();
                    } else if (hasCurr) {
                        Voucher.cancelEdit();
                        parentTr.find('.curr-code').focus().click();
                    }
                }
            }
        }
    });
    return inputList;
}

Voucher._instantItem = function($_obj, url, origin, defaultId) {
    if (defaultId) {
        defaultId = ['id', defaultId];
    } else {
        defaultId = -1;
    }
    return $_obj.combo({
        data: url/*function(){
         return '/bs/itemView?m=findAll&itemType=Inventory';
         if(!(parent[data] || parent.parent[data] || top[data])) {
         return ''
         } else {
         return '/bs/itemView?m=findAll&itemType=Inventory';
         //return parent[data] || parent.parent[data] || top[data];
         }
         }*/,
        ajaxOptions: {
            formatData: function(data) {
                return data.data.items;
            }
        },
        formatText: function(data) {
            return data.number + ' ' + data.name;
        },
        defaultSelected: defaultId,
        value: 'id',
        //forceSelection: false,
        editable: true,
        callback: {
            onChange: function(data) {
                var cellVal = origin.prev('.cell_val');
                var curData = cellVal.data('itemsData') || {};
                var thisId = $_obj[0].id;
                curData[thisId] = data;
                cellVal.data('itemsData', curData);
                if (thisId === 'itemCH') {
                    var $_unit = origin.parents('tr.entry_item').find('.unit');
                    if (data.unit) {
                        $_unit.text(data.unit);
                    } else {
                        $_unit.text($_unit.data('unit'));
                    }
                }
            }
        }
    }).getCombo();
}

Voucher._instantXDItem = function($_obj, origin, defaultId) {
    if (defaultId) {
        defaultId = ['id', defaultId];
    } else {
        defaultId = 0;
    }
    return $_obj.combo({
        data: [{
                "id": "2",
                "name": "非限定"
            }, {
                "id": "1",
                "name": "限定"
            }],
        defaultSelected: defaultId,
        text: 'name',
        value: 'id',
        //forceSelection: false,
        editable: false,
        callback: {
            onChange: function(data) {
                var cellVal = origin.prev('.cell_val');
                var curData = cellVal.data('itemsData') || {};
                var thisId = $_obj[0].id;
                curData[thisId] = data;
                cellVal.data('itemsData', curData);
            }
        }
    }).getCombo();
}

Voucher._checkItems = function($_obj) {
    var success = true;
    if (Voucher.isItem && Voucher.isItem.is(':visible')) {
        var comboList = $_obj || Voucher.isItem.find("li:visible");
        comboList.each(function(i) {
            if ($(this).find('.ui-combo-wrap').getCombo().getSelectedIndex() === -1) {
                $(this).find('.ui-combo-wrap').getCombo().activate();
                Public.tips({type: 1, content: '核算项目不能为空！'});
                success = false;
                return false;
            }
        });
    }
    return success ? true : false;
};
/**
 *生成金额输入域
 */
Voucher.createMoneyFeild = function() {
    Voucher.moneyFeild = $('<input type="text" class="edit_money" autocomplete="off" />').numberField({
        decimal: true,
        max: 999999999.99,
        keyEnable: false
    }).bind('keydown', function(e) {
        var keyValue = e.which, value = $(this).val(), parentTd = $(this).parent(),
                parentTr = $(this).parents('tr.entry_item'), nextTr = parentTr.next();
        if (e.shiftKey && (keyValue === ENTER || keyValue === TAB)) {
            parentTr.find('.col_subject').trigger('click');
            return false;
        }

        if (parentTd.hasClass('col_debite')) {
            parentTr.find('.credit_val').data('realValue', 0).text('');
        } else {
            parentTr.find('.debit_val').data('realValue', 0).text('');
        }

        switch (keyValue) {
            case ENTER:
            case TAB:
                e.preventDefault();
                if ($(this).val() != '') {
                    if (nextTr.length == 0) {
                        Voucher.addEntry();
                        nextTr = parentTr.next();
                    }
                    ;
                    if (Math.abs($(this).val()) >= 1000000000) {
                        Public.tips({type: 2, content: '只能输入10亿以下的金额！'});
                        $(this).select();
                        return;
                    }
                    nextTr.find('.col_summary').trigger('click');
                } else {
                    if (parentTd.hasClass('col_debite')) {
                        parentTd.next().trigger('click');
                    }
                    ;
                }
                return false;
                break;

            case SPACE:
                var targetTd;
                if (parentTd.hasClass('col_debite')) {
                    targetTd = parentTr.find('.col_credit');
                } else {
                    targetTd = parentTr.find('.col_debite');
                }
                $(this).val('');
                targetTd.find('.cell_val').text(value).data('realValue', value);
                targetTd.trigger('click');
                return false;
                break;
        }
    }).bind('keyup', function(e) {
        var equalCode = $.browser.opera ? 107 : $.browser.mozilla ? 61 : 187;
        if (e.keyCode == equalCode) {
            Voucher.setBalanceValue($(this));
        }
    }).bind('focus', function() {
        Voucher.originalAmount = $(this).val() === '' ? 0 : Number($(this).val()).toFixed(2);
    }).bind('blur', function() {
        var currAmount = $(this).val() === '' ? 0 : Number($(this).val()).toFixed(2);
        if (!currAmount) {
            return;
        }
        //值更改反算处理
        if (Voucher.originalAmount !== currAmount) {
            var parentTr = $(this).parents('tr.entry_item');
            var subjectVal = parentTr.find('.subject_val').data('subjectInfo');
            if (subjectVal) {
                var hasQtyaux = subjectVal.isQtyaux;
                var hasCurr = subjectVal.isCur;

                if (hasCurr) {
                    var originalVal = Number(parentTr.find('.original').val());
                    if (originalVal) {
                        parentTr.find('.rate').val((currAmount / originalVal).toFixed(3) * 1);
                        return;
                    }
                }
                if (hasQtyaux) {
                    var quantityVal = Number(parentTr.find('.quantity').val());
                    if (quantityVal) {
                        parentTr.find('.unit-price').val((currAmount / quantityVal).toFixed(3) * 1);
                        return;
                    }
                }
            }
        }
    });

    Voucher.moneyFeild.calculator({callback: function() {
        }});
}

/**
 *试算金额平衡
 */
Voucher.setBalanceValue = function(input) {
    input = $(input);
    input.prev().data('realValue', 0).text('');//清零原来的值
    var totalDebit = Voucher.getTotalAccountAmount('debit');
    var totalCredit = Voucher.getTotalAccountAmount('credit');
    var balanceValue = totalDebit - totalCredit;
    if (input.prev().hasClass('debit_val')) {
        balanceValue = totalCredit - totalDebit;
    }
    input.val(balanceValue.toFixed(2));
}

/**
 *设置金额的显示值和正负样式
 */
Voucher.showAmout = function(obj, amount) {
    obj = $(obj);
    amount = parseFloat(amount);
    if (isNaN(amount)) {
        return;
    }
    amount = amount.toFixed(2);
    obj.data('realValue', amount);
    amount = Math.round(amount * 100);
    if (amount >= 0) {
        obj.removeClass('money-negative');
    } else {
        amount = -amount;
        obj.addClass('money-negative');
    }
    obj.text(amount || '');
}

/**
 *计算合计金额
 */
Voucher.calTotalAmount = function() {
    var totalDebit = Voucher.getTotalAccountAmount('debit');
    var totalCredit = Voucher.getTotalAccountAmount('credit');
    Voucher.showAmout($('#debit_total'), totalDebit);
    Voucher.showAmout($('#credit_total'), totalCredit);
    if (totalDebit == totalCredit && totalDebit != 0) {
        var amountWords = Voucher.formatAmountToChinese(totalDebit);
        $('#capAmount').text(amountWords);
        if (totalDebit > 0) {
            $('#capAmount').removeClass('money-negative');
        } else {
            $('#capAmount').addClass('money-negative');
        }
        ;
    } else {
        $('#capAmount').text('');
    }
};


/**
 *将阿拉伯金额转换成中文金额
 @param {number string} example: 100
 @return {string} example: '一百元整'
 */
Voucher.formatAmountToChinese = function(amount) {
    amount = parseFloat(amount);
    if (isNaN(amount)) {
        return;
    }// || Math.abs(amount) > 99999999999.99
    amount = Math.round(amount * 100);
    var isInt = amount % 100 == 0 ? true : false;
    var numArr = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
    var unitArr = ["分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"];
    var resultStr = '', num, unitIdx, len, zeroCount = 0;
    if (amount == 0) {
        return '零元整';
    }
    ;
    if (amount < 0) {
        resultStr += '负';
        amount = -amount;
    }
    amount = amount.toString();
    len = amount.length;
    for (var i = 0; i < len; i++) {
        num = parseInt(amount.charAt(i));
        unitIdx = len - 1 - i;
        if (num == 0) {
            //元 万 亿 输出单位
            if (unitIdx == 2 || unitIdx == 6 || unitIdx == 11) {
                resultStr += unitArr[unitIdx];
                zeroCount = 0;
            } else {
                zeroCount++;
            }
        } else {
            if (zeroCount > 0) {
                resultStr += '零';
                zeroCount = 0;
            }
            ;
            resultStr = resultStr + numArr[num] + unitArr[unitIdx];
        }
    }
    ;

    if (isInt) {
        resultStr += '整';
    }
    ;

    return resultStr;
};


/**
 *计算借方或贷方总数
 *@param ｛string｝ 'credit' or 'debit'
 *@return {number} 计算出的金额
 */
Voucher.getTotalAccountAmount = function(account) {
    var objs, total = 0, val;
    if (account == 'credit') {
        objs = $('#voucherTable .entry_item .credit_val');
    } else if (account == 'debit') {
        objs = $('#voucherTable .entry_item .debit_val');
    }
    $.each(objs, function(idx) {
        val = parseFloat($(this).data('realValue'));
        if (isNaN(val)) {
            return;
        }
        total += val;
    });
    return total.toFixed(2);
};


/**
 * 设置录入金额焦点位置
 * @param	{JqueryElement}		当前所在行
 * @param	{object}	 所选科目数据
 * 规则：1.如果借方或者贷方金额不为空，则不为空的获取焦点；
 *	    2.如果两者为空，则依据科目信息获取焦点（科目默认为借方则借方获取焦点，科目默认为贷方则贷方获取焦点）
 *       3.如果科目信息为空，则默认借方获取焦点
 */
Voucher.setAmountFocus = function($obj, data) {
    var debiteCol = $obj.find(".col_debite"), debiteAmount = debiteCol.find(".debit_val").text(),
            creditCol = $obj.find(".col_credit"), creditAmount = creditCol.find(".credit_val").text();
    if (debiteAmount !== "") {
        debiteCol.trigger("click");
        return;
    } else if (creditAmount !== "") {
        creditCol.trigger("click");
        return;
    }
    ;
    if (data == null) {
        debiteCol.trigger("click");
        return;
    }
    if (false !== $(".entry_item").index($obj)) {
        debiteCol.trigger("click");
        return;
    }
    ;
    if (data.dc == 1) {//借方
        debiteCol.trigger("click");
        return;
    } else if (data.dc == -1) {//贷方
        creditCol.trigger("click");
        return;
    }
    ;
};



/**
 *增加分录
 */
Voucher.addEntry = function(obj) {
    var addTr = ['<tr class="entry_item">',
        '<td class="col_operate"><div class="operate"><a title="增加分录" class="add"></a><a title="删除分录" class="del"></a></div></td>',
        '<td class="col_summary" data-edit="summary"><div class="cell_val summary_val"></div></td>',
        '<td class="col_subject" data-edit="subject"><div class="cell_val subject_val"></div></td>',
        '<td class="col_option"><div class="option"><a class="selSub">科目</a></div></td>',
        '<td class="col_quantity"><div class="cell_val quantity_val"></div></td>',
        '<td class="col_currency"><div class="cell_val curr_val"></div></td>',
        '<td class="col_debite" data-edit="money"><div class="cell_val debit_val"></div></td>',
        '<td class="col_credit" data-edit="money"><div class="cell_val credit_val"></div></td>',
        '</tr>'].join('');
    if (obj) {
        obj.before(addTr);
    } else {
        $("#voucherTable > tbody").append(addTr);
    }
}


/**
 *删除分录
 */
Voucher.delEntry = function(entryObj) {
    Voucher.cancelEdit();
    if ($('#voucherTable .entry_item').length > 2) {
        //删除扩展行 
        if (entryObj.next('tr.extra_item').length > 0) {
            entryObj.next('tr.extra_item').remove();
        }
        ;
        entryObj.remove();
        Voucher.calTotalAmount();
    } else {
        Public.tips({type: 2, content: '至少保留二条分录！'});
    }
}

/**
 *获取分录数据
 */
Voucher.getEntriesData = function() {
    var entriesData = [];
    var entryId = 0;
    var entriesItems = $('#voucherTable tbody tr.entry_item');
    Voucher.noQuantity = [], Voucher.noOriginal = [];	//检查数量、原币是否为空或0
    for (var i = 0; i < entriesItems.length; i++) {
        var entryItem = entriesItems.eq(i), subjectVal = entryItem.find(".subject_val");
        var summary = entryItem.find('.summary_val').html();
        var subjectInfo = subjectVal.data("subjectInfo");
        var itemsData = subjectVal.data('itemsData');
        var debit = entryItem.find('.debit_val').data("realValue") || 0;
        var credit = entryItem.find('.credit_val').data("realValue") || 0;
        //科目和金额都为空 则该分录无效
        if (debit == 0 && credit == 0 && !subjectInfo) {
            continue;
        }
        ;

        if (!subjectInfo) {
            Public.tips({type: 2, content: '请选择科目！'});
            window.setTimeout(function() {
                Voucher.editCell(entryItem.find(".col_subject"));
            }, 0);
            return false;
        }
        ;

        if (debit == 0 && credit == 0) {
            Public.tips({type: 2, content: '请录入借贷方金额！'});
            window.setTimeout(function() {
                Voucher.setAmountFocus(entryItem, subjectInfo);
            }, 0);
            return false;
        }
        entryId = i + 1;

        var itemId = 0, customId = 0, deptId = 0, supplierId = 0, empId = 0, inventoryId = 0, projectId = 0, limited = subjectInfo.limited;
        //自定义类别ID，客户ID，部门ID，供应商ID，职员ID，存货ID, 项目ID,限定/非限定
        if (subjectInfo.isItem) {
            itemsData.itemCH ? inventoryId = itemsData.itemCH.id : '';
            itemsData.itemGYS ? supplierId = itemsData.itemGYS.id : '';
            itemsData.itemKH ? customId = itemsData.itemKH.id : '';
            itemsData.itemXM ? projectId = itemsData.itemXM.id : '';
            itemsData.itemBM ? deptId = itemsData.itemBM.id : '';
            itemsData.itemZY ? empId = itemsData.itemZY.id : '';
            itemsData.itemZDY ? itemId = itemsData.itemZDY.id : '';
            itemsData.itemSFXD ? limited = itemsData.itemSFXD.id : subjectInfo.limited;
        }
        var quantity = 0, units = '', unitPrice = 0;
        if (subjectInfo.isQtyaux) {
            quantity = $.trim(entryItem.find('.quantity').val()) || 0; //数量
            units = entryItem.find('.unit').text(); //单位
            unitPrice = $.trim(entryItem.find('.unit-price').val()) || 0; //单价
            if (quantity === 0) {
                Voucher.noQuantity.push(entryId);
            }
        }

//        var cur = SYSTEM.CURRENCY, rate = 1.0, amountFor = (debit != 0 ? debit : credit);
//        if (subjectInfo.isCur) {
//            cur = entryItem.find('.curr-code').val();
//            rate = $.trim(entryItem.find('.rate').val()) || 0;
//            if (cur !== SYSTEM.CURRENCY) {
//                amountFor = $.trim(entryItem.find('.original').val()) || 0;
//                if (amountFor === 0) {
//                    Voucher.noOriginal.push(entryId);
//                }
//            }
//        }

        var dataItem = {
            voucherId: -1, //凭证ID
            id: -1, //凭证分录ID
            explanation: summary, //摘要
            accountId: subjectInfo.id, //科目ID
            accountNumber: subjectInfo.number, //科目编码
            accountName: subjectInfo.fullName, //科目名称
            dc: debit != 0 ? 1 : -1, //借贷方向
            amount: debit != 0 ? debit : credit, //发生额
            itemClassId: subjectInfo.itemClassId, //自定义核算类别项目
            itemClassName: '', //自定义核算类别名称
            itemId: itemId, //自定义核算项目ID
            itemNumber: '', //自定义核算项目编码
            itemName: '', //自定义核算项目名称
            customId: customId, //客户ID
            customNumber: '', //客户编码
            customName: '', //客户名称
            deptId: deptId, //部门ID
            deptNumber: '', //部门编码
            deptName: '', //部门名称
            supplierId: supplierId, //供应商ID
            supplierNumber: '', //供应商编码
            supplierName: '', //供应商名称
            empId: empId, //职员ID
            empNumber: '', //职员编码
            empName: '', //职员名称
            inventoryId: inventoryId, //存货ID
            projectId: projectId, //项目ID
            projectNumber: '', //项目编码
            projectName: '', //项目名称
            qty: quantity, //数量
            unit: units, //单位
            price: unitPrice, //单价
            cur: "RMB", //所选币别
            rate: "1", //汇率
            amountFor: "RMB", //原币
            settleCode: 0, //结算方式
            settleno: '', //结算号
            settleDate: '', //结算日期
            transbal: 0, //往来核销金额本币
            transbalFor: 0, //往来核销金额原币
            transDate: '', //往来日期
            transno: '', //往来编号
            match: 0, //往来核销状态，1为已核销，0为未核销,-1为部分核销
            qtyAux: false, //是否数量金额辅助核算 对应科目上的isQtyaux
            trans: false, //是否往来核算 对应科目上的isTrans
            entryId: entryId, //凭证分录序号
            transId: -1, //往来核销ID
            control: false, //往来受控
            accountId2: -1, //对方科目ID
            acctCur: "RMB", //对方币别
            limited: limited //限定/非限定
        };
        console.debug(dataItem);
        entriesData.push(dataItem);
    }
    ;

    if (entriesData.length < 2) {
        Public.tips({type: 2, content: '请录入至少二条有效分录！'});
        return false;
    }
    ;

    return JSON.stringify(entriesData);

}

/**
 *获取凭证数据
 */
Voucher.getVoucherData = function() {
    data_flag = true;
    var entriesItems = $('#voucherTable tbody tr.entry_item');
    var vchWordCombo = $('#vchMarkSelect');
    var data_val = $('#vch_date').val();
    if (data_flag === false) {
        Public.tips({type: 1, content: '日期格式录入有误！如：2012-08-08。'});
        $("#vch_date").select().focus();
        return false;
    }
    var first_summary = entriesItems.eq(0).find('.summary_val');
    if (first_summary.html() === "") {
        Public.tips({type: 2, content: '第1条分录摘要不能为空！'});
        window.setTimeout(function() {
            Voucher.editCell(entriesItems.eq(0).find(".col_summary"));
        }, 0);
        return false;
    }
    var totalDebit = $('#debit_total').data('realValue');
    var totalCredit = $('#credit_total').data('realValue');
    if (totalDebit != totalCredit) {
        Public.tips({type: 2, content: '录入借贷不平！'});
        return false;
    }
    ;
    var entries = Voucher.getEntriesData();

    if (entries) {
        var voucherData = {
            id: -1,
            groupId: $("#vchMarkSelect").val(), //凭证字ID
            number: $('#vchNumSelect').val(), //凭证号
//			  voucherNo: vchWordCombo.val() + '-' + $('#vch_num').val(),	//凭证字号
            attachments: parseInt($('#vch_attach').val()) || 0, //附单据
            date: $("#vch_date input").val(), //凭证日期
            year: $('#vch_year').text(), //凭证年份
            period: $('#vch_period').text(), //凭证期间
            yearPeriod: parseInt($('#vch_year').text()) * 100 + parseInt($('#vch_period').text()), //凭证年期
            entries: entries, //分录数
            debitTotal: totalDebit, //贷方总额
            creditTotal: totalCredit, //借方总额
            explanation: first_summary.html(), //摘要
//			  internalind: VCH_DATA.internalind ? VCH_DATA.internalind : '',//单据类型
//			  transType: VCH_DATA.transType ? VCH_DATA.transType : '',//业务类型			  
            userName: $('#vch_people').text(), //制单人				  
            checked: 0, //是否审核
            checkName: "", //审核人
            posted: 0, //是否过账
            modifyTime: $('#vch_date').val(), //操作时间
            ownerId: 1, //凭证拥有人ID
            checkerId: 1//凭证审核人ID
        }
        console.debug(voucherData);
        return voucherData;
    } else {
        return false;
    }
}

Voucher.firstFocus = function() {
    $("#voucherTable td.col_summary").eq(0).trigger("click");
}

/**
 * 设置凭证号
 * @param	{String}	凭证字
 * @param	{String}	凭证日期
 */
Voucher.setNum = function(mark, date) {
    var date = date || $("#vch_date").val();
    $.ajax({
        type: 'POST',
        url: '/gl/voucher?m=getvchNum',
        data: {"vchdate": date, "groupId": mark, vchId: PAGE.vchID},
        dataType: "json",
        success: function(data, textStatus) {
            if (!data || !data.data) {
                Public.tips({type: 1, content: '账套期间加载失败！'});
                return;
            }
            if (data.data.period == 0) {
                Public.tips({type: 2, content: '时间不能早于系统启用时间！'});
                $("#period").text("0");
                $("#year").text("0");
                return;
            }
            //设置凭证号
            $("#vch_num").val(data.data.vchNum);
            $("#vch_period").text(data.data.period);
            $("#vch_year").text(data.data.year);
            yearPeriod = data.data.yearPeriod;
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Public.tips({type: 1, content: '账套期间加载失败！'});
        }
    });
};

Voucher.resetPeriod = function(vchDate) {
    var gourpId = $('#vch_mark').getCombo().getValue();
    $.ajax({
        type: "post",
        url: '/gl/voucher?m=getvchNum',
        data: {"vchdate": vchDate, "groupId": gourpId, vchId: PAGE.vchID},
        dataType: "json",
        success: function(data, textStatus) {
            if (data.data.period == 0) {
                Public.tips({type: 2, content: '时间不能早于系统启用时间！'});
                $("#period").text("0");
                $("#year").text("0");
                return;
            }
            //data.year年份  data.period期间
            $("#vch_period").text(data.data.period);
            $("#vch_year").text(data.data.year);
            $("#vch_num").val(data.data.vchNum);
            yearPeriod = data.data.yearPeriod;
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            Public.tips({type: 1, content: '账套期间加载失败！'});
        }
    });
};


Voucher.showCheckBalance = function($_obj) {
    var $_parent = $_obj.parent();
    var id = $_obj.data('id');
    var number = $_obj.data('number');
    var cur = '0';
    var $_currCode = $_obj.parents('tr').find('.curr-code');
    if ($_currCode.length > 0) {
        cur = $_currCode.val();
    }
    var offset = $_obj.offset();
    $_parent.addClass('show');
    if (!Voucher.balancePop) {
        $_parent.addClass('show');
        Voucher.balancePop = $('<div class="balance-pop" />').html('<b></b><a href="#" class="close" title="关闭">关闭</a><div class="check-balance">查询中...</div>').appendTo('body')

        Voucher.balancePop.find('.close').on('click', function(e) {
            e.preventDefault();
            $_parent.removeClass('show');
            Voucher.balancePop.hide().find('.check-balance').html('查询中...');
        });
    }
    ;
    Voucher.balancePop.css({
        "top": (offset.top + $_obj.height() + 5) + "px",
        "left": (offset.left - 75) + "px"
    }).show();
    var ctn = Voucher.balancePop.find('.check-balance');
    var year_period = yearPeriod;
    //科目余额查询，修改凭证日期到以后期间的，统一传当前期间，包括联查明细账
    if (Number(yearPeriod) > Number(SYSTEM.CURPERIOD)) {
        year_period = SYSTEM.CURPERIOD;
    }
    $.ajax({
        type: "POST",
        url: '/Accounting/AccountingSubject/ajax_QueryBalance',
        data: {number: number, yearperiod: year_period, currency: cur},
        dataType: "json",
        success: function(data, textStatus) {
            if (data.status == 200) {
                ctn.html('<strong>' + data.data.bal + '</strong><a href="/books/subsidiary-ledger.html?id=' + id + '&number=' + number + '&periodFrom=' + year_period + '&periodTo=' + year_period + '" rel="pageTab" tabid="book-subsidiaryLedger" parentOpen="true" tabTxt="明细账">明细账</a>');
            } else {
                ctn.html('余额查询失败！');
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            ctn.html('余额查询失败！');
        }
    });
}
Voucher.resetTable = function() {
    $('.voucherWrap').removeClass().addClass('wrapper');
    Voucher.colTotal.attr('colspan', '3');
    $("#voucherTable > tbody").html('');
    var differ = 4;
    while (differ--) {
        Voucher.addEntry();
    }
    ;
    if (Voucher.isItem) {
        Voucher.items.KH = Voucher.items.GYS = Voucher.items.ZY = Voucher.items.XM = Voucher.items.BM = Voucher.items.CH = Voucher.items.SFXD = Voucher.items.ZDY = null;
        Voucher.isItem = null;
        $('#isItem').html('').remove()
    }
};
Voucher._addHandle = function(type, url, callback) {
    if (Voucher.curEditCell) {
        //Voucher.cancelEdit();
        if (!Voucher.cancelEdit()) {
            return false;
        }
        ;
    }
    var voucherData = Voucher.getVoucherData();
    if (voucherData) {
        if (type === 'edit') {
            voucherData.id = PAGE.vchID;
        }
        var confirmInfo = '', noQuantityLen = Voucher.noQuantity.length, noOriginalLen = Voucher.noOriginal.length;

        if (noQuantityLen > 0 || noOriginalLen > 0) {
            if (noQuantityLen > 0) {
                confirmInfo = '当前第' + Voucher.noQuantity.join('、') + '条分录的数量值为空，';
            }
            if (noOriginalLen > 0) {
                if (noQuantityLen > 0) {
                    confirmInfo += '<br />第' + Voucher.noOriginal.join('、') + '条分录原币值为空，确定继续吗？';
                }
                confirmInfo = '当前第' + Voucher.noOriginal.join('、') + '条分录原币值为空，确定继续吗？';
            } else {
                confirmInfo += '确定继续吗？'
            }

            $.dialog.confirm(confirmInfo, function() {
                Public.postAjax(url, {"vchData": JSON.stringify(voucherData)}, callback);
            }, function() {

            });
        } else {
            //url:请求地址， params：传递的参数{...}， callback：请求成功回调  
            Public.postAjax(url, {"vchData": JSON.stringify(voucherData)}, callback);
        }
    }

}